package com.slorgs.business.utils;

import com.gateway.common.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WebsocketCertificationUtil {

    private static final Logger log = LoggerFactory.getLogger(WebsocketCertificationUtil.class);

    private static final WebsocketCertificationUtil wcu = new WebsocketCertificationUtil();

    private static final Map<String, Map<String, Object>> map = new HashMap<>();

    public static WebsocketCertificationUtil getInstance() {
        return wcu;
    }

    public void add(String key, boolean value) {
        Map<String, Object> objectMap = new HashMap<>();
        objectMap.put("result", value);
        objectMap.put("expiredTime", System.currentTimeMillis() + (30 * Constants.MINUTE));
        map.put(key, objectMap);
    }

    public boolean getKey(String key) {
        return map.get(key) != null;
    }

    public boolean validate(String key) {
        Map<String, Object> map1 = map.get(key);
        if (map1 != null) {
            return (boolean) map1.get("result");
        }
        return false;
    }

    static {
        new Thread(() -> {
            while (true) {
                try {
                    List<String> list = new ArrayList<>();
                    map.forEach((k, v) -> {
                        long o = (long) v.get("expiredTime");
                        if (System.currentTimeMillis() > o) {
                            list.add(k);
                        }
                    });
                    list.forEach(map::remove);
                    Thread.sleep(30000);
                } catch (InterruptedException e) {
                    log.error("定时清理长连接过期key异常", e);
                }
            }
        }).start();
    }
}
